package com.jh.netty.instruction.datapacket;

import com.jh.netty.instruction.DataPacket;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

/**
 * 控制器历史事件回应数据
 *
 * @see com.jh.netty.instruction.DataPacketCMD#CMD_GET_EVENT
 */
@Setter
@Getter
@ToString
public class ControllerHistoryResponseData {

    /**
     * 报编号  1byte  0-255
     * <p>
     * 编号随机 不连续
     */
    private String packetNum;

    /**
     * 事件日期  2byte
     */
    private String eventDate;

    /**
     * 事件时间  2byte
     */
    private String eventTime;

    /**
     * 事件代码  1byte
     */
    private String eventCode;

    /**
     * 点地址 1byte
     */
    private String pointAddress;

    /**
     * 卡的区号  2byte
     */
    private String cardAreaCode;

    /**
     * 卡号  2byte
     */
    private String cardNum;

    public static ControllerHistoryResponseData parse(DataPacket dp) {
        return parse(dp.getDataCodeText());
    }

    public static ControllerHistoryResponseData parse(String dataCodeText) {
        ControllerHistoryResponseData chrd = new ControllerHistoryResponseData();
        chrd.packetNum = dataCodeText.substring(0, 2);
        chrd.eventDate = dataCodeText.substring(2, 6);
        chrd.eventTime = dataCodeText.substring(6, 10);
        chrd.eventCode = dataCodeText.substring(10, 12);
        chrd.pointAddress = dataCodeText.substring(12, 14);
        chrd.cardAreaCode = dataCodeText.substring(14, 18);
        chrd.cardNum = dataCodeText.substring(18, 22);
        return chrd;
    }

    public LocalDateTime getDateTime() {
        long d = Long.parseLong(eventDate, 16);
        LocalDate ld = LocalDate.of(2000, 1, 1);
        LocalDate date = ld.plusDays(d);

        long s = Long.parseLong(eventTime, 16);
        LocalTime lt = LocalTime.of(0, 0, 0);
        LocalTime time = lt.plusSeconds(s);

        return LocalDateTime.of(date, time);
    }
}
